import os
import time
from datetime import datetime
from email._header_value_parser import get_attribute

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager


class Driver:

    # 驱动
    _driver = None

    # 浏览器参数设置：页面加载策略, 智能等待时间，是否无头模式
    def __init__(self, load = "normal", wait_time = 3, isHeadless = False):
        # 驱动版本管理
        driver_path = ChromeDriverManager().install()
        # 创建驱动对象
        options = webdriver.ChromeOptions()
        options.page_load_strategy = load
        options.headless = isHeadless
        self._driver = webdriver.Chrome(service=Service(driver_path), options=options)
        self._driver.implicitly_wait(wait_time)

    # 常用操作：
    # 1. 关闭当前标签页
    def quit(self):
        self._driver.quit()

    # 2. 关闭浏览器（析构）
    def __del__(self):
        self._driver.close()

    # 3. 访问网址
    def get(self, url):
        self._driver.get(url)

    # 4. 网页元素查找: 默认按照 选择器查找 ret : WebElement
    def find_element(self, key, mode = By.CSS_SELECTOR):
        return self._driver.find_element(mode, key)

    # 5. 点击操作
    def click(self, element):
        element.click()

    # 6. 输入操作
    def send_keys(self, element, value):
        element.send_keys(value)

    # 7. 清除输入
    def clear(self, element):
        element.clear()

    # 8. 获取网页标题和url
    def title(self):
        return self._driver.title

    def current_url(self):
        return self._driver.current_url

    # 9. 获取文本值
    def txt(self, element):
        return element.text

    # 10. 获取属性值
    def value(self, key):
        return get_attribute(key)

    #11. 设置窗口大小
    # 最小化
    def minimize_window(self):
        self._driver.minimize_window()

    # 最大化
    def maximize_window(self):
        self._driver.maximize_window()

    # 全屏
    def fullscreen(self):
        self._driver.fullscreen_window()

    # 自定义
    def set_window_size(self, width, height):
        self._driver.set_window_size(width, height)

    # 12. 导航条操作
    # 前进
    def forward(self):
        self._driver.forward()

    # 后退
    def back(self):
        self._driver.back()

    # 刷新
    def refresh(self):
        self._driver.refresh()

    # 13. 屏幕截图
    def save_screenshot(self, filename):
        self._driver.save_screenshot(filename)

    def find_elements(self, key, mode = By.CSS_SELECTOR):
        return self._driver.find_elements(mode, key)

    def execute_script(self, script):
        self._driver.execute_script(script)

# 创建 Driver
gdriver = Driver()